package test;

import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class NetworkUtils {

    public static String dialAndRetrieveInterfaceName(String interfaceName, String username, String password) throws Exception {
        String osName = System.getProperty("os.name").toLowerCase();
        String ipAddress = null;

        if (osName.contains("win")) {
            // Windows 拨号
            Process dialProcess = Runtime.getRuntime().exec("rasdial " + interfaceName + " " + username + " " + password);
            BufferedReader reader = new BufferedReader(new InputStreamReader(dialProcess.getInputStream(), "GBK")); // 使用GBK编码
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            dialProcess.waitFor();

            // 获取IP地址和网卡名称
            Process ipProcess = Runtime.getRuntime().exec("ipconfig");
            BufferedReader ipReader = new BufferedReader(new InputStreamReader(ipProcess.getInputStream(), "GBK")); // 使用GBK编码
            String ipLine;

            while ((ipLine = ipReader.readLine()) != null) {
                if (ipLine.contains(interfaceName)) {
                    while ((ipLine = ipReader.readLine()) != null) {
                        if (ipLine.contains("IPv4")) {
                            String[] parts = ipLine.split(":");
                            if (parts.length > 1) {
                                ipAddress = parts[1].trim();
                                System.out.println("IP Address: " + ipAddress);
                                return ipAddress;
                            }
                        }
                    }
                }
            }

            ipProcess.waitFor();
        } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("aix")) {
            // Linux 拨号
            Process dialProcess = Runtime.getRuntime().exec("sudo pon " + interfaceName + " user " + username + " password " + password);
            BufferedReader reader = new BufferedReader(new InputStreamReader(dialProcess.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            dialProcess.waitFor();

            // 获取IP地址和网卡名称
            Process ipProcess = Runtime.getRuntime().exec("ip addr show");
            BufferedReader ipReader = new BufferedReader(new InputStreamReader(ipProcess.getInputStream()));
            String ipLine;

            while ((ipLine = ipReader.readLine()) != null) {
                if (ipLine.contains(interfaceName)) {
                    while ((ipLine = ipReader.readLine()) != null) {
                        if (ipLine.contains("inet")) {
                            String[] parts = ipLine.split(" ");
                            for (String part : parts) {
                                if (part.contains("/")) {
                                    ipAddress = part.split("/")[0];
                                    System.out.println("IP Address: " + ipAddress);
                                    return ipAddress;
                                }
                            }
                        }
                    }
                }
            }

            ipProcess.waitFor();
        } else {
            throw new Exception("Unsupported operating system: " + osName);
        }

        return null;
    }

    /**
     * 获取所有网卡的名称
     * @return
     */
    public List<String> getNetworkInfo() {
        LinkedList<String> nameList = new LinkedList<>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                System.out.println("Network Interface Name: " + networkInterface.getName());
                nameList.add(networkInterface.getName());
                System.out.println("Display Name: " + networkInterface.getDisplayName());
                System.out.println("----------------------------------------");
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return nameList;
    }

    // 使用指定网卡名称或IP地址下载指定资源
    public static void downloadResource(String url, String interfaceOrIpAddress, String destinationFile) throws Exception {
        InetAddress inetAddress = null;

        // 尝试将输入解析为IP地址
        try {
            inetAddress = InetAddress.getByName(interfaceOrIpAddress);
            System.out.println("Using IP Address: " + inetAddress.getHostAddress());
        } catch (UnknownHostException e) {
            // 如果解析失败，则认为输入的是网卡名称
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface = null;
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                if (ni.getName().equals(interfaceOrIpAddress)) {
                    networkInterface = ni;
                    break;
                }
            }

            if (networkInterface == null) {
                throw new Exception("Network interface not found: " + interfaceOrIpAddress);
            }

            // 获取网络接口的IP地址
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress ia = inetAddresses.nextElement();
                System.out.println("Found address: " + ia.getHostAddress()); // 调试信息
                if (!ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                    inetAddress = ia;
                    break;
                }
            }

            if (inetAddress == null) {
                throw new Exception("No valid IP address found for interface: " + interfaceOrIpAddress);
            }
        }

        // 使用指定的IP地址下载资源
        URL resourceUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) resourceUrl.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setRequestProperty("Host", resourceUrl.getHost());
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");

        // 创建一个Socket并绑定到指定的本地地址
        Socket socket = new Socket();
        socket.bind(new InetSocketAddress(inetAddress, 0));
        socket.connect(new InetSocketAddress(resourceUrl.getHost(), resourceUrl.getPort() == -1 ? 80 : resourceUrl.getPort()), 5000);

        // 获取输入输出流
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();

        // 发送HTTP请求
        String request = "GET " + resourceUrl.getFile() + " HTTP/1.1\r\n" +
                "Host: " + resourceUrl.getHost() + "\r\n" +
                "User-Agent: Mozilla/5.0\r\n" +
                "Connection: close\r\n\r\n";
        os.write(request.getBytes());
        os.flush();

        // 读取HTTP响应
        try (InputStream in = is;
             FileOutputStream out = new FileOutputStream(destinationFile)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            boolean headerEnded = false;
            while ((bytesRead = in.read(buffer)) != -1) {
                if (!headerEnded) {
                    String header = new String(buffer, 0, bytesRead);
                    int endIndex = header.indexOf("\r\n\r\n");
                    if (endIndex != -1) {
                        headerEnded = true;
                        out.write(buffer, endIndex + 4, bytesRead - endIndex - 4);
                    }
                } else {
                    out.write(buffer, 0, bytesRead);
                }
            }
        }

        socket.close();
        System.out.println("Downloaded resource to: " + destinationFile);
    }

    // 获取所有宽带连接的名称
    public List<String> getDialupConnectionNames() throws Exception {
        String osName = System.getProperty("os.name").toLowerCase();
        LinkedList<String> connectionNames = new LinkedList<>();

        if (osName.contains("win")) {
            // Windows 拨号连接
            Process process = Runtime.getRuntime().exec("rasphone -l");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK")); // 使用GBK编码
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    connectionNames.add(line.trim());
                }
            }
            process.waitFor();
        } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("aix")) {
            // Linux 拨号连接
            Process process = Runtime.getRuntime().exec("nmcli connection show type pppoe");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            boolean inConnections = false;
            while ((line = reader.readLine()) != null) {
                if (line.contains("NAME")) {
                    inConnections = true;
                    continue;
                }
                if (inConnections && !line.trim().isEmpty()) {
                    String[] parts = line.split("\\s+");
                    if (parts.length > 0) {
                        connectionNames.add(parts[0]);
                    }
                }
            }
            process.waitFor();
        } else {
            throw new Exception("Unsupported operating system: " + osName);
        }

        return connectionNames;
    }
    public static void main(String[] args) {
//        String ipAddress = null;
//        try {
//            String connectionName = "eth38";
//            String username = "MZFTTH075300380424@16900.gd";
//            String password = "123456";
//            ipAddress = dialAndRetrieveInterfaceName(connectionName, username, password);
//            System.out.println("IP Address: " + ipAddress);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        try {
//            // 使用IP地址下载资源
//            downloadResource("https://dl.hostbuf.com/finalshell3/finalshell_windows_x64.exe", ipAddress, "D:\\resource2.exe");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            NetworkUtils networkUtils = new NetworkUtils();
            List<String> connectionNames = networkUtils.getDialupConnectionNames();
            System.out.println("Dialup Connection Names:");
            for (String name : connectionNames) {
                System.out.println(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
